<?php
declare(strict_types=1);

namespace App\WebSocket\Chat;

use Swoft\Redis\Redis;
use Swoft\Task\Task;
use Swoft\WebSocket\Server\Annotation\Mapping\MessageMapping;
use Swoft\WebSocket\Server\Annotation\Mapping\WsController;
use Swoft\WebSocket\Server\Message\Message;
use Swoft\WebSocket\Server\Message\Request;
use Tool\AjaxReturn;
use App\Until\SM4;
use Swoft\Bean\Annotation\Mapping\Inject;
use App\Common\Component\RedisComponent;

/**
 * 客服相关
 * Class ClientController
 * @package App\WebSocket\Chat
 * @WsController(prefix="server")
 */
class ServerController
{
    use RedisComponent;
    /**
     * @Inject()
     * @var SM4
     */
    private SM4 $sm4;
    
    /**
     * 客服初始化
     * @MessageMapping(command="initChat")
     */
    public function initChat(Request $request): array
    {
        $fd = $request->getFd();

        $data = AjaxReturn::sendData([
            'fd' => $fd,
            'cmd' => 'client.setServerFd'
        ]);


        server()->broadcast(json_encode($data), [], [$fd]);

        return AjaxReturn::sendData([
            'fd' => $fd,
//            'cmd' => $request->getMessage()->getCmd()
        ]);

    }

    /**
     * @MessageMapping()
     * @param Request $request
     * @return Message
     */
    public function sendMessage(Request $request): array
    {

        $data = $request->getMessage()->getData();

        vdump($data);
       
//        $data = $this->sm4->decrypt($data['token'],  $data['msg']);
        
//         vdump($data);
        
//         vdump($this->sm4->decrypt($this->redis->get("token"), $data['data']));
       
//         $userId = Redis::get($data['token']);
        
        $fd = Redis::hGet('fd', $data['sender']);
        
        vdump("sender:".$fd);
        
        if (!$fd) {
           return AjaxReturn::errorWebsocket('好友没有登录');
        }
       
        server()->sendTo($fd, json_encode(AjaxReturn::sendWebsocketMessage($data['msg'])));

//         Task::async('SaveToDataBase', 'work', $data);

        return AjaxReturn::sendWebsocketSuccess('');

    }

    /**
     * 客服初始化
     * @MessageMapping(command="send")
     */
    public function send(Request $request): array
    {
        return [
            'msg' => '客服发送消息了'
        ];
    }
}